
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
using namespace std;
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        cout << "User: TcpClient ip_address port" << endl;
        return 1;
    }
    //1. 创建socket
    int socket = ::socket(AF_INET,SOCK_STREAM,0);
    if(socket < 0)
    {
        cout << "socket fail " << endl;
        return 2;
    }
    //2. 设置
    string server_ip = argv[1];
    int server_port = stoi(argv[2]);

    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    int n = ::connect(socket,(sockaddr*)&server_addr,sizeof(server_addr));
    if(n < 0)
    {
        cout << "connect fail" << endl;
        return 3;
    }
    cout << "connect success,n:" << n << endl;

    while(true)
    {
        string msg;
        cout <<"please enter" << endl;
        getline(cin,msg);
        //3. 发送信息
        int n = write(socket,msg.c_str(),msg.size());
        if(n > 0)
        {
            char buffer[1024];
            n = read(socket,buffer,sizeof(buffer) - 1);
            if(n > 0)
            {
                buffer[n] = 0;
                cout << buffer << endl;
            }
            else
                break;
        }
        else
            break;
    }
    close(socket);
    return 0;
}